<!--
 * @Author: 徐伟杰
 * @Date: 2022-09-22 15:43:14
 * @LastEditors: 黄宇/Hyuishine
 * @LastEditTime: 2025-02-18 15:36:20
 * @Description: 
 * @Email: 1529315455@qq.com
 * @Company: 3xData
 * @youWant: add you want
-->
<template>
  <view class="container_page">
    <!-- 顶部自定义导航栏 -->
    <action-bar :options="navOptions" />

    <uni-section title="基本信息" type="line">
      <template v-for="(formItem, i) in form">
        <view :class="formItem.title === '报告附件' ? 'formItem1' :
          formItem.type === 'doubleRow' ? 'formItem2' : 'formItem'" :key="i">
          <template v-if="formItem.slot">
            <template v-if="formItem.title === '报告附件'">
              <view class="file">
                <view class="label">{{ formItem.title }}：</view>
                <view class="btn" @click="openPDF(baseApiUrl + '/profile' + formData[formItem.value])">
                  查看文件
                </view>
              </view>
            </template>
          </template>
          <template v-else-if="formItem.type === 'doubleRow'">
            <view class="doubleRow">
              <view class="lable">{{ formItem.title }}：</view>
              <view class="value">{{ formData[formItem.value] }}</view>
            </view>
          </template>
          <template v-else>
            <view class="label">{{ formItem.title }}</view>
            <view class="value">{{ formData[formItem.value] }}</view>
          </template>
        </view>
      </template>
    </uni-section>

    <uni-section title="上传整改信息" type="line" v-if="done">
      <template v-for="(formItem, i) in formRectify">
        <view :class="formItem.title === '整改方案附件' ? 'formItem4' :
          formItem.type === 'doubleRow' ? 'formItem2' : 'formItem'" :key="i">
          <template v-if="formItem.slot">
            <template v-if="formItem.title === '整改方案附件'">
              <view class="doubleRow">
                <view class="label">{{ formItem.title }}：
                  <span style="color: red">(文件格式要求:JPG、PNG、PDF)</span>
                </view>
                <uni-file-picker class="btns" fileMediatype="all" v-if="!disabled" ref="imageValues"
                  :value="listSelected" mode="grid" :limit="20" file-extname="png,jpg,pdf"
                  :v-model="baseImgUrl + formData[formItem.value]" @select="select($event, formItem.value)"
                  @progress="progress" @success="success" @fail="fail" />
                <image mode="widthFix" v-if="formData[formItem.value]" class="images"
                  @click="imageView(baseApiUrl + formData[formItem.value])"
                  :src="baseApiUrl + '/' + formData[formItem.value]" />
                <view v-else @click="openPDF(baseApiUrl + formData[formItem.value])">
                  <button size="mini" type="default"
                    style="width:200rpx;overflow: auto;word-break:break-all;">查看文件</button>
                </view>
              </view>
            </template>
          </template>
          <template v-else-if="formItem.type === 'doubleRow'">
            <view class="doubleRow">
              <view class="lable">{{ formItem.title }}：</view>
              <picker mode="date" class="value" :disabled="disabled" :value="date" :start="startDate" :end="endDate"
                @change="bindDateChange">
                <view class="uni-input">{{ date }}</view>
              </picker>
            </view>
          </template>
          <template v-else>
            <view class="label">{{ formItem.title }}</view>
            <input class="value" :disabled="disabled" v-model="formData[formItem.value]" />
          </template>
        </view>
      </template>
    </uni-section>

    <uni-section title="上传整改结论" type="line">
      <template v-for="(formItem, i) in formConclusion">
        <view :class="formItem.title === '整改结论附件' ? 'formItem4' :
          formItem.type === 'doubleRow' ? 'formItem2' : 'formItem'" :key="i">
          <template v-if="formItem.slot">
            <template v-if="formItem.title === '整改结论附件'">
              <view class="doubleRow">
                <view class="label">{{ formItem.title }}：
                  <span style="color: red">(文件格式要求:JPG、PNG、PDF)</span>
                </view>
                <uni-file-picker class="btns" fileMediatype="all" ref="imageValues" v-if="!disabled"
                  :value="listSelected1" mode="grid" :limit="20" file-extname="png,jpg,pdf"
                  :v-model="baseImgUrl + '/' + formData[formItem.value]" @select="select($event, formItem.value)"
                  @progress="progress" @success="success" @fail="fail" />
                <image mode="widthFix" v-if="formData[formItem.value]" class="images"
                  @click="imageView(baseApiUrl + formData[formItem.value])"
                  :src="baseApiUrl + '/' + formData[formItem.value]" />
                <view v-if="formData[formItem.value] && formData[formItem.value].indexOf('.pdf') !== -1"
                  @click="openPDF(baseApiUrl + formData[formItem.value])">
                  <button size="mini" type="default"
                    style="width:200rpx;overflow: auto;word-break:break-all;">查看文件</button>
                </view>
              </view>
            </template>
          </template>
          <template v-else-if="formItem.radio">
            <view class="label">{{ formItem.title }}</view>
            <radio-group class="radioBox" @change="radioChange">
              <label class="flex justify-start" v-for="(item, index) in items" :key="item.value">
                <radio :value="item.value" :disabled="disabled" style="transform:scale(0.7)"
                  :checked="index === current" />
                <view class="margin-left-xs">{{ item.name }}</view>
              </label>
            </radio-group>
          </template>
          <template v-else-if="formItem.type === 'doubleRow'">
            <view class="doubleRow">
              <view class="lable">{{ formItem.title }}：</view>
              <picker mode="date" class="value" :value="date1" :disabled="disabled" :start="startDate" :end="endDate"
                @change="bindDateChange1">
                <view class="uni-input">{{ date1 }}</view>
              </picker>
            </view>
          </template>
          <template v-else>
            <view class="label">{{ formItem.title }}</view>
            <input class="value" :disabled="disabled" v-model="formData[formItem.value]" />
          </template>
        </view>
      </template>
    </uni-section>

    <uni-section title="监管提示" type="line">
      <template v-for="(formItem, i) in forSsupervise">
        <view :class="formItem.title === '附件' ? 'formItem1' :
          formItem.type === 'doubleRow' ? 'formItem2' : 'formItem'" :key="i">
          <template v-if="formItem.slot">
            <template v-if="formItem.title === '附件'">
              <view class="file">
                <view class="label">{{ formItem.title }}：</view>
                <view class="btn" @click="openPDF(baseApiUrl + formData[formItem.value])"
                  v-if="formData[formItem.value] != undefined">
                  查看文件
                </view>
              </view>
            </template>
          </template>
          <template v-else-if="formItem.type === 'doubleRow'">
            <view class="doubleRow">
              <view class="lable">{{ formItem.title }}：</view>
              <view class="value">{{ formData[formItem.value] }}</view>
            </view>
          </template>
          <template v-else>
            <view class="label">{{ formItem.title }}</view>
            <view class="value">{{ formData[formItem.value] }}</view>
          </template>
        </view>
      </template>
    </uni-section>
    <view style="height: 100rpx;"></view>
    <web-view v-if="showAn" :src="pdfFileUrls"></web-view>

    <view class="save_btn" @click="save_btn" v-if="!disabled">
      <view class="btn">保存</view>
    </view>

  </view>
</template>

<script>
import { baseApiUrl, baseImgUrl } from '@/config.js';
export default {
  data() {
    const currentDate = this.getDate({
      format: true
    })
    return {
      done: false,
      showAn: false, // 打开pdf文件
      pdfFileUrls: null, // pdf文件路径
      date: currentDate,
      date1: currentDate,
      // 保存时的防抖
      disabledShow: false,
      baseApiUrl: baseApiUrl,
      baseImgUrl: baseImgUrl,
      // 导航栏参数
      navOptions: {
        left: {
          icon: "back",
        },
        center: {
          title: "故障处理",
        },
      },

      form: [
        {
          title: '报告编号',
          value: "reportCode"
        },
        // {
        //   title: '报告生效日期',
        //   value: "name"
        // },
        {
          title: '机构名称',
          value: "agencyName"
        },
        {
          title: '项目名称',
          value: "projectName"
        },
        {
          title: '项目负责人',
          value: "projectHeadName"
        },
        // {
        //   title: '故障发现时间',
        //   value: "name"
        // },
        {
          title: '项目地址',
          value: "projectAddress"
        },
        // {
        //   title: '故障描述',
        //   value: "name",
        //   type: 'doubleRow'
        // },
        {
          title: '报告附件',
          value: "fileUrl",
          slot: true
        }
      ],

      formRectify: [
        {
          title: '负责人',
          value: "rectificationPlanList.head",
        },
        {
          title: '联系电话',
          value: "rectificationPlanList.headPhone"
        },
        {
          title: '整改方案日期',
          value: "rectificationPlanList.planDate",
          type: 'doubleRow'
        },
        {
          title: '整改方案描述',
          value: "rectificationPlanList.planDescription",

        },
        {
          title: '整改方案附件',
          value: "rectificationPlanList.planFileUrls",
          slot: true
        },
      ],
      formConclusion: [
        {
          title: '填表人',
          value: "rectificationConclusionList.preparer"
        },
        {
          title: '联系电话',
          value: "rectificationConclusionList.preparerPhone"
        },
        {
          title: '整改日期',
          value: "rectificationConclusionList.rectificationDate",
          type: 'doubleRow'
        },
        {
          title: '整改情况',
          value: "rectificationConclusionList.isRectification",
          radio: true
        },
        {
          title: '整改描述',
          value: "rectificationConclusionList.rectificationDescription",
        },
        {
          title: '整改结论附件',
          value: "rectificationConclusionList.rectificationFileUrls",
          slot: true
        },
      ],
      forSsupervise: [
        {
          title: '被提示单位',
          value: "tipsList.unit"
        },
        {
          title: '提示日期',
          value: "tipsList.tipDate"
        },
        {
          title: '提示人',
          value: "tipsList.prompter"
        },
        {
          title: '提示描述',
          value: "tipsList.description",
          type: 'doubleRow'
        },
        {
          title: '附件',
          value: "tipsList.fileUrls",
          slot: true
        },
      ],
      items: [
        {
          value: '0',
          name: '未整改',
        },
        {
          value: '1',
          name: '已整改',
          checked: 'true'
        },
        {
          value: '2',
          name: '整改中'
        }
      ],
      current: 0,
      formData: null, // 通过后端接口获取到的表单数据
      reportId: null, // 上个页面获取到的reportId
      listSelected: [],
      listSelected1: [],

      imgPath: '/common/upload',

      disabled: false,

      planId: null,
      conclusionId: null,
      loading: false,
    }
  },
  computed: {
    startDate() {
      return this.getDate('start');
    },
    endDate() {
      return this.getDate('end');
    }
  },
  onLoad(e) {
    this.reportId = e.reportId
    this.getList()
  },
  methods: {
    getList() {
      if (this.loading) return

      this.loading = true
      uni.showLoading({
        title: '正在加载请稍后',
        mask: true
      });

      let data = {
        reportId: this.reportId
      }
      this.$store.dispatch('get_faultInfo_falut', data).then(({ data }) => {
        this.formData = data
        this.planId = data.rectificationPlanList[0]?.planId || null;
        this.conclusionId = data.rectificationConclusionList[0]?.conclusionId || null;
        if (data.rectificationPlanList.length == 1) {
          this.formData['rectificationPlanList.head'] = data.rectificationPlanList[0]?.head
          this.formData['rectificationPlanList.headPhone'] = data.rectificationPlanList[0]?.headPhone
          this.date = data.rectificationPlanList[0]?.planDate
          this.formData['rectificationPlanList.planDescription'] = data.rectificationPlanList[0]?.planDescription
          this.formData['rectificationPlanList.planFileUrls'] = data.rectificationPlanList[0]?.planFileUrls

          this.done = true
        } else {
          //! 2023-05-25 14:40:44 没有数据时自动带出安全管理人员的数据 需求029
          this.$store.dispatch('responsibleContact').then(res => {
            if (res && res.code == 200) {
              this.formData['rectificationPlanList.head'] = res.data.manageName
              this.formData['rectificationPlanList.headPhone'] = res.data.managePhone
              this.done = true
            }
          })
        }
        if (data.rectificationConclusionList.length == 1) {
          this.formData['rectificationConclusionList.preparer'] = data.rectificationConclusionList[0]?.preparer
          this.formData['rectificationConclusionList.preparerPhone'] = data.rectificationConclusionList[0]?.preparerPhone
          this.date1 = data.rectificationConclusionList[0]?.rectificationDate
          this.formData['rectificationConclusionList.rectificationDescription'] = data.rectificationConclusionList[0]?.rectificationDescription
          this.formData['rectificationConclusionList.rectificationFileUrls'] = data.rectificationConclusionList[0]?.rectificationFileUrls
          this.current = Number(data.rectificationConclusionList[0].isRectification)
        }
        if (data.tipsList.length == 1) {
          this.formData['tipsList.unit'] = data.tipsList[0]?.unit
          this.formData['tipsList.tipDate'] = data.tipsList[0]?.tipDate
          this.formData['tipsList.prompter'] = data.tipsList[0]?.prompter
          this.formData['tipsList.description'] = data.tipsList[0]?.description
          this.formData['tipsList.fileUrls'] = data.tipsList[0]?.fileUrls

          // this.current = Number(data.rectificationConclusionList[0].isRectification)
        }
      }).finally(() => {
        let timer = setTimeout(() => {
          this.loading = false
          uni.hideLoading();
          clearTimeout(timer)
        }, 3000);
      })
    },
    // 图片预览
    imageView(url) {
      uni.previewImage({
        current: 0,
        urls: [url]
      })
    },
    // 返回一个弹窗
    errorTip(msg) {

    },
    save_btn() {
      if (this.loading) return

      this.loading = true
      uni.showLoading({
        title: '正在加载请稍后',
        mask: true
      });

      let timer = setTimeout(() => {
        this.loading = false
        uni.hideLoading();
        clearTimeout(timer)
      }, 3000);

      let that = this
      const phone = this.formData['rectificationPlanList.headPhone'] || null
      const preparerPhone = this.formData['rectificationConclusionList.preparerPhone'] || null
      const reg_tel = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
      if (phone == null || preparerPhone == null) {
        uni.showToast({
          title: '请输入联系电话',
          icon: "none",
        });
        return
      }
      if (!reg_tel.test(phone) && !reg_tel.test(preparerPhone)) {
        uni.showToast({
          title: '请输入正确的联系电话',
          icon: "none",
        });
        return
      }

      if (this.formData['rectificationPlanList.head'] == null) {
        uni.showToast({
          title: '请输入负责人',
          icon: "none",
        });
        return
      }
      // if (this.formData['rectificationPlanList.planDescription'] == null) {
      //   uni.showToast({
      //     title: '请输入整改方案描述',
      //     icon: "none",
      //   });
      //   return
      // }
      // if (this.formData['rectificationPlanList.planFileUrls'] == null) {
      //   uni.showToast({
      //     title: '请输入整改方案附件',
      //     icon: "none",
      //   });
      //   return
      // }
      if (this.formData['rectificationConclusionList.preparer'] == null) {
        uni.showToast({
          title: '请输入填表人',
          icon: "none",
        });
        return
      }

      if (this.formData['rectificationConclusionList.rectificationDescription'] == null) {
        uni.showToast({
          title: '请输入整改描述',
          icon: "none",
        });
        return
      }

      if (this.formData['rectificationConclusionList.rectificationFileUrls'] == null) {
        uni.showToast({
          title: '请输入整改结论附件',
          icon: "none",
        });
        return
      }
      let data = {
        rectificationPlanList: [{
          reportId: this.reportId,
          head: this.formData['rectificationPlanList.head'],
          headPhone: this.formData['rectificationPlanList.headPhone'],
          planDate: this.date || this.formData['rectificationPlanList.planDate'],
          planDescription: this.formData['rectificationPlanList.planDescription'],
          planFileUrls: this.formData['rectificationPlanList.planFileUrls'],
          planId: this.planId,
        }],
        rectificationConclusionList: [{
          reportId: this.reportId,
          preparer: this.formData['rectificationConclusionList.preparer'],
          preparerPhone: this.formData['rectificationConclusionList.preparerPhone'],
          rectificationDate: this.date1 || this.formData['rectificationConclusionList.rectificationDate'],
          rectificationDescription: this.formData['rectificationConclusionList.rectificationDescription'],
          rectificationFileUrls: this.formData['rectificationConclusionList.rectificationFileUrls'],
          isRectification: this.current,
          conclusionId: this.conclusionId,
        }]
      }

      if (that.disabledShow) return
      that.disabledShow = true
      this.loading = true
      uni.showModal({
        title: '提示',
        content: '确定是否保存吗？',
        showCancel: true,
        success(res) {
          if (res.confirm) {
            that.$store.dispatch('insert_planAnd_conclusion', data).then(res => {
              if (res.code == 200) {
                uni.showToast({
                  title: '上传成功',
                  icon: "none",
                });
                uni.reLaunch({
                  url: '/pages_workTableChild/fault/index'
                })
                that.disabledShow = false
              }
            })
              .finally(() => {
                let timer = setTimeout(() => {
                  this.loading = false
                  uni.hideLoading();
                  clearTimeout(timer)
                }, 3000);
              })
          } else {
            that.disabledShow = false
          }
        }
      })
    },
    radioChange(evt) {
      for (let i = 0; i < this.items.length; i++) {
        if (this.items[i].value === evt.detail.value) {
          this.current = i;
          break;
        }
      }
    },
    bindDateChange: function (e) {
      this.date = e.detail.value
      this.formData['rectificationPlanList.planDate'] = e.detail.value
    },
    bindDateChange1: function (e) {
      this.date1 = e.detail.value
      this.formData['rectificationConclusionList.rectificationDate'] = e.detail.value
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 60;
      } else if (type === 'end') {
        year = year + 2;
      }
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    // toPhotoCatch () {

    // },
    // 获取上传状态
    select(e, key) {
      if (e.tempFiles.length > 0) {
        let size = e.tempFiles[0].size
        if (size <= 1024 * 1024 * 20) {
          uni.uploadFile({
            url: baseApiUrl + this.imgPath, //仅为示例，非真实的接口地址
            filePath: e.tempFilePaths[0],
            name: 'file',
            formData: {
              'user': 'test'
            },
            success: (uploadFileRes) => {
              let dist = JSON.parse(uploadFileRes.data)
              if (dist.code == 200) {
                this.formData[key] = dist.fileName
                console.log(this.formData[key])
              } else {
                uni.showToast({
                  title: '上传失败',
                  icon: "none",
                  duration: 2000
                })
              }
            }
          });
        } else {
          this.$refs.imageValues[0].clearFiles()
          uni.showToast({
            title: '文件过大',
            icon: "none",
            duration: 2000
          })
        }
      } else {

      }

    },
    // 获取上传进度
    progress(e) {
      console.log("上传进度：", e);
    },

    // 上传成功
    success(e) {
      console.log("上传成功");
    },

    // 上传失败
    fail(e) {
      console.log("上传失败：", e);
    },

    openPDF(row) {
      let that = this
      this.pdfFileUrls = row
      uni.showLoading({
        title: '打开文件中！'
      });
      uni.getSystemInfo({
        success: res => {
          // console.log(res.platform, res.platform === 'android')
          if (res.platform === 'android') {
            that.showAn = false
            const url = row
            uni.downloadFile({
              url,
              success: ({ statusCode, tempFilePath }) => {
                console.log(statusCode)
                if (statusCode === 200) {
                  uni.saveFile({
                    tempFilePath,
                    success: (res) => {
                      uni.openDocument({
                        filePath: res.savedFilePath,
                        success: (res) => {
                          uni.hideLoading();
                          console.log('成功打开文档')
                        }
                      })
                    },
                    fail: () => {
                      console.log('下载失败')
                    }
                  })
                }
              }
            })
          } else {
            that.showAn = true
            uni.hideLoading();
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

::v-deep .uni-section {
  margin-top: 0;
  background-color: transparent;
}

.container_page {
  background: #f4f5f5;
  min-height: 100vh;
  font-size: 28rpx;


  .formItem,
  .formItem1,
  .formItem2,
  .formItem4 {
    width: calc(100% - 40rpx);
    min-height: 110rpx;
    display: flex;
    margin: 0 auto 24rpx;
    border-radius: 20rpx;
    padding: 0 24rpx;
    background-color: #fff;

    .label {
      color: #333;
      font-size: 28rpx;
      font-weight: 600;
      line-height: 36rpx;
      width: 35%;
    }

    .value {
      flex: 1;
      text-align: right;
      max-width: 75%;
      font-size: 28rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .formItem {
    align-items: center;

    .radioBox {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      padding: 24rpx;
    }
  }

  .formItem1 {
    padding: 24rpx;
    align-items: center;

    .file {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      height: 60rpx;
      width: 100%;

      .label {
        color: #333;
        font-size: 28rpx;
        font-weight: 600;
        line-height: 36rpx;
        width: 100%;
      }

      .btn {
        padding: 5rpx 20rpx;
        border: 1rpx solid #e5e5e5;
        border-radius: 20rpx;
        background: $OVERALL_CONFIRM_BUTTON_COLOR;
        color: #fff;
        min-width: 180rpx;
        text-align: center;
        font-size: 28rpx;
        min-height: 60rpx;
      }
    }

    .doubleRow {
      display: flex;
      flex-direction: row;
      height: 260rpx;
      padding-top: 20rpx;
      width: 100%;

      .value {
        flex: 1;
        text-align: right;
      }

      .content {
        margin-left: 24rpx;
      }
    }
  }

  .formItem2 {
    align-items: center;

    .value {
      flex: 1;
      text-align: right;
    }

    .doubleRow {
      display: flex;
      flex-direction: row;
      width: 100%;

      .lable {
        color: #333;
        font-size: 28rpx;
        font-weight: 600;
        line-height: 36rpx;
        width: 35%;
      }

      .value {
        flex: 1;
        text-align: right;
      }
    }
  }

  .formItem4 {
    display: flex;
    padding: 24rpx;

    .label {
      color: #333;
      font-size: 28rpx;
      font-weight: 600;
      line-height: 36rpx;
      width: 100%;
    }

    .value {
      flex: 1;
      text-align: right;
    }

    .doubleRow {
      display: flex;
      flex-direction: column;
      justify-content: flex-start;

      .content {
        margin-left: 24rpx;
      }

      ::v-deep .btns .uni-file-picker__files .files-button {
        uni-button {
          background: $OVERALL_CONFIRM_BUTTON_COLOR;
          color: #fff;
          margin-top: 20rpx;
        }
      }

      .images {
        width: 240rpx;
        height: 240rpx;
        border: 1rpx solid #e5e5e5;
        margin-top: 20rpx;
        border-radius: 20rpx;
      }
    }
  }

  .save_btn {
    width: 100%;
    height: 100rpx;
    display: flex;
    font-size: 32rpx;
    border-radius: 15rpx;
    position: fixed;
    bottom: 0;
    background-color: #fff;
    border-top: 1rpx solid #e5e5e5;

    .btn {
      width: calc(100% - 40rpx);
      margin: 10rpx 20rpx;
      text-align: center;
      height: 80rpx;
      font-size: 28rpx;
      line-height: 80rpx;
      color: #fff;
      background: $OVERALL_CONFIRM_BUTTON_COLOR;
    }
  }
}

.radioBox {
  width: 100%;
  display: flex;
  flex-direction: row-reverse;
}
</style>